﻿using System.Linq;
using DG.Tweening;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
using Gp.Scripts.Data.Skills;
using Gp.Scripts.Core;
using Gp.Scripts.Core.Skill;
using TMPro;
using UnityEngine;

namespace Gp.Scripts.GUI {
    public class SkillToolTipsController : MonoBehaviour {
        [SerializeField] private Transform pivot;

        [SerializeField] private TMP_Text title;
        [SerializeField] private TMP_Text description;
        [SerializeField] private CanvasGroup canvas;

        [SerializeField] private TMP_Text costText;

        [SerializeField] private Transform disableReason;
        [SerializeField] private TMP_Text disableReasonText;
        


        private Vector3 _orgScale;

        private void Start() {
            _orgScale = canvas.transform.localScale;
            Hide();
        }


        private TweenerCore<float, float, FloatOptions> _core;
        private TweenerCore<Vector3,Vector3,VectorOptions> _core2;


        public void Display(BoxSkillButton button) {
            var info = button.RenderInfo;
            pivot.transform.position = button.transform.position;

            title.text = info.NameText;
            description.text = info.DescriptionText;


            ResolveCost(button.SkillEntity);


            canvas.transform.localScale = _orgScale * .2f;

            if (!button.SkillEntity.CanSelect().Result(out var rs)) {
                disableReason.gameObject.SetActive(true); 
                disableReasonText.text = rs.Text();
            }else {
                disableReason.gameObject.SetActive(false);
                disableReasonText.text = "";
            }
            
            
            _core?.Kill();
            _core2?.Kill();
            _core = canvas.DOFade(1, .2f);
            _core2 = canvas.transform.DOScale(_orgScale, 0.2f);
        }


        private void ResolveCost(SkillEntity skill) {
            var label = "";
            if (skill is MagicSkillEntity magic) {
                var magicCost = magic.ActualMagicCost;
                label += "算力点 " + magicCost;
            }
            else {
                var costInfo = skill.SkillCostInfo();
                if (costInfo.Costs.Count == 0) {
                    label += "无";
                }
                else {
                    label = costInfo.Costs.Aggregate(label,
                        (current, cost) => current + (cost.Type.LabelName() + " " + cost.Amount + "/"));
                    label = label.Trim('/');
                }
            }

            costText.text = label;
        }


        public void Hide() {
            _core?.Kill();
            canvas.alpha = 0;
            title.text = "";
            description.text = "";
        }
    }
}